#include "Ship.h"
#include "renderer\DebugRenderer.h"
#include "..\..\Constants.h"

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
Ship::Ship() : ds::DynamicSpriteNode("Ship","TexturesMaterial",ds::SCM_MODULATE) , m_Blocked(true) , m_BulletAngle(0.0f) , m_Rotation(0.0f) , m_Magnetic(false) {
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
Ship::~Ship(void) {
	delete m_Circle;
	delete m_Hero;	
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void Ship::loadContent(ds::ResManager& resourceManager) {
	
	m_Position = ds::Vec2(500,680);
	m_Hero = new ds::Sprite(m_Position,ds::Rect(50,0,115,70));

	m_Circle = new ds::Sprite(ds::Vec2(300,300),ds::Rect(50,115,158,158),ds::Color(0.9f,0.9f,0.9f,0.8f),1.0f,1.0f,0.0f);			
	
	m_LeftHandle = gEngine->getCollisionDetector().addCircle(ds::Vec2(0,0),ds::Vec2(29,35),29,SHIP_ID);
	m_RightHandle = gEngine->getCollisionDetector().addCircle(ds::Vec2(0,0),ds::Vec2(29,35),29,SHIP_ID);
	setBlocked(true);
}

// -----------------------------------------------------------------------------
// Blocks the player from moving and centers it in the middle of the screen
// -----------------------------------------------------------------------------
void Ship::setBlocked(bool blocked) {
	m_Blocked = blocked;
	if ( m_Blocked ) {
		updatePosition(ds::Vec2(500,680));
	}
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void Ship::update(const float elapsed) {
	if ( !m_Blocked ) {
		ds::Vec2 p = getPosition();	
		float y = gEngine->getMousePosY();
		float x = gEngine->getMousePosX();
		ds::Vec2 mp(x,y);
		ds::Vec2 diff = mp - p;
		float dist = mp.distance(p);
		if ( dist > 25.0f ) {				
			p.add(diff.x*0.05f,0.0f);
		}
		updatePosition(p);
		
	}
	m_Rotation += 45.0f * elapsed;
	if ( m_Rotation > 360.0f ) {
		m_Rotation -= 360.0f;
	}
	m_Circle->rotation = DEGTORAD(m_Rotation);	
	addSprite(m_Hero);
	if ( m_Magnetic ) {
		addSprite(m_Circle);
	}
}

// -----------------------------------------------------------------------------
// Updates the player position
// -----------------------------------------------------------------------------
void Ship::updatePosition(const ds::Vec2& pos) {
	m_Position = pos;
	m_Hero->position = m_Position;	
	gEngine->getCollisionDetector().setPosition(m_LeftHandle,pos);
	gEngine->getCollisionDetector().setPosition(m_RightHandle,pos);
	ds::Vec2 cp = pos;
	cp.sub(22.0f,45.0f);
	m_Circle->position = cp;
}